package accounting.service;

import accounting.model.Asset;
import accounting.model.Cost;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Transactional
public class AssetServiceImpl implements AssetService {
    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @SuppressWarnings("unchecked")
    public List<Asset> findAll() {
        Query query = getEntityManager().createNamedQuery("Asset.findAll");
        return query.getResultList();
    }

    private void save(Asset asset) {
        if (asset.getId() == null) {
            // new
            em.persist(asset);
        } else {
            // update
            em.merge(asset);
        }
    }

    public void remove(int id) {
        Asset asset = find(id);
        if (asset != null) {
            em.remove(asset);
        }
    }

    private EntityManager getEntityManager() {
        return em;
    }

    public Asset find(int id) {
        return em.find(Asset.class, id);
    }

    public void add(Asset asset) {
        this.save(asset);
    }

    public void update(Asset asset) {
        this.save(asset);
    }

}
